package com.qinyh.view;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;

import com.qinyh.activity.R;
import com.qinyh.controller.Controller;
import com.qinyh.entity.Page;
import com.qinyh.entity.Point;
import com.qinyh.util.DebugUtil;
import com.qinyh.util.PathCalculator;
import com.qinyh.util.TemplateStore;
import com.qinyh.util.TextUtil;

public class PageView extends View {
	// 页面翻动位置
	public final static int LEFT_TOP = 0;// 左上
	public final static int CENTER_TOP = 1;// 中上
	public final static int RIGHT_TOP = 2;// 右上
	public final static int CENTER_RIGHT = 3;// 右中
	public final static int RIGHT_BOTTOM = 4;// 右下
	public final static int CENTER_BOTTOM = 5;// 中下
	public final static int LEFT_BOTTOM = 6;// 左下
	public final static int CENTER_LEFT = 7;// 左中

	public final static int PAGE_NEXT_BACK = 11;// 向下一页翻页后退
	public final static int PAGE_NEXT_NEWPAGE = 21;// 向下一页翻页前进
	public final static int PAGE_PRE_BACK = 12;// 向上一页翻页后退
	public final static int PAGE_PRE_NEWPAGE = 22;// 向上一页翻页前进
	
	public static final int ADDNOTE=Menu.FIRST+20;
	public static final int VIEWNOTE=Menu.FIRST+21;
	
	private boolean isFlipper = false;

	public Controller controller;
	private Context ctt;
	private PathCalculator calculator;
	private Point startPoint;
	private Point currentPoint;
	private Point end;
	// 当前页面翻动位置
	private int pageCase = 1;
	public Activity activity;
	public PageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		ctt = context;
		controller = new Controller(ctt);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (!isFlipper) {
			Log.v("debug", "debug fontSize");
			controller.height = this.getHeight();
			controller.width = this.getWidth();
			Page page = controller.getCurrentPage();
			Paint paint = new Paint();
			paint.setTextSize(TemplateStore.fontSize);
			canvas.drawColor(Color.WHITE);
			paint.setColor(Color.BLACK);
			String s = "";
			if (page != null) {
				s = page.getPageContext();
			} else {
				s = "";
			}
			TextUtil tu = new TextUtil(s, 0, 40, this.getWidth(),
					this.getHeight(), Color.WHITE, Color.BLACK, 0,
					TemplateStore.fontSize);
			tu.InitText();
			tu.DrawText(canvas);
		} else {
			try {
				drawNextPage(canvas);
				drawCurrentPage(canvas);
				drawScroll(canvas);
			} catch (Exception exp) {
				DebugUtil.debug("debug", exp);
			}
		}
	}

	// 画当前页
	private void drawCurrentPage(Canvas canvas) {
		try {
			Page page = controller.getCurrentPage();
			if (page != null) {
				Path path = calculator.getCurrentPath();
				canvas.clipPath(path);
				canvas.drawColor(Color.WHITE);
				Paint paint = new Paint();
				paint.setTextSize(TemplateStore.fontSize);
				paint.setColor(Color.BLACK);
				String s = page.getPageContext() + "";
				TextUtil tu = new TextUtil(s, 0, 40, this.getWidth(),
						this.getHeight(), Color.WHITE, Color.BLACK, 0,
						TemplateStore.fontSize);
				tu.InitText();
				tu.DrawText(canvas);
			} else
				canvas.drawColor(Color.BLACK);
		} catch (Exception e) {
			DebugUtil.debug("debug", e);
		}
	}

	// 画翻页
	private void drawScroll(Canvas canvas) {
		canvas.restore();
		// draw shador
		Path path = calculator.getBackShadorPath();
		canvas.clipPath(path);
		Paint paint = new Paint();
		paint.setShader(calculator.getBackShador());
		paint.setColor(Color.BLACK);
		canvas.drawPath(path, paint);
		// draw pre-shador
		canvas.restore();
		Path pathp = calculator.getForwardShadorPath();
		canvas.clipPath(pathp);
		// paint.setColor(Color.RED);
		canvas.drawPath(path, paint);
		paint.setShader(calculator.getForwardShador());
		canvas.drawPath(pathp, paint);
		canvas.restore();

		// draw white
		Path wPath = calculator.getPageBackPath();
		canvas.clipPath(wPath);
		Paint paint1 = new Paint();
		paint1.setColor(Color.WHITE);
		canvas.drawPath(wPath, paint1);

		// draw white shader
		canvas.restore();
		Path aPath = calculator.getBackShadorPath();
		canvas.clipPath(aPath);
		Paint paint2 = new Paint();
		paint2.setColor(Color.WHITE);
		paint2.setAntiAlias(true);
		paint2.setShader(calculator.getBackShador());
		canvas.drawPath(aPath, paint2);
	}

	// 画下一页
	private void drawNextPage(Canvas canvas) {
		Page page = null;
		boolean isStart = false;
		if (calculator.getCorner().getX() == 0
				|| (calculator.getCorner().getX() < this.getWidth() && calculator
						.getCorner().getY() == 0)) {
			page = controller.getPrePage();
			isStart = true;
		} else
			page = controller.getNextPage();
		if (page != null) {
			Paint paint = new Paint();
			canvas.drawColor(Color.WHITE);
			paint.setTextSize(TemplateStore.fontSize);
			paint.setColor(Color.BLACK);
			String s = page.getPageContext() + "";
			TextUtil tu = new TextUtil(s, 0, 40, this.getWidth(),
					this.getHeight(), Color.WHITE, Color.BLACK, 0,
					TemplateStore.fontSize);
			tu.InitText();
			tu.DrawText(canvas);
		} else {
			if (isStart) {
				canvas.drawColor(Color.WHITE);
			} else {
				Paint paint = new Paint();
				paint.setColor(Color.RED);
				canvas.drawText("The End", this.getWidth() / 2,
						this.getHeight() / 2, paint);
			}

		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (isAutoFlipper)
			return false;
		long eventTime=0;
		long downTime=0;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			isFlipper = true;
			startPoint = new Point();
			startPoint.setX(event.getX());
			startPoint.setY(event.getY());
			calculator = new PathCalculator();
			calculator.setHeight(this.getHeight());
			calculator.setWidth(this.getWidth());
			calculator.setStartPoint(startPoint);
			calculator.setHeight(this.getHeight());
			calculator.setWidth(this.getWidth());
			calculator.addFlipperType();
			break;
		case MotionEvent.ACTION_MOVE:
			if (calculator.getFlipperType() == PageView.RIGHT_BOTTOM
					|| calculator.getFlipperType() == PageView.CENTER_RIGHT
					|| calculator.getFlipperType() == PageView.CENTER_LEFT) {
				if (currentPoint == null)
					currentPoint = new Point();
				currentPoint.setX(event.getX());
				currentPoint.setY(event.getY());
				calculator.setTouchPoint(currentPoint);
				postInvalidate();
			}
			break;
		case MotionEvent.ACTION_UP:
				end = new Point();
				end.setX(event.getX());
				end.setY(event.getY());
				if (calculator.getFlipperType() == PageView.RIGHT_BOTTOM
						|| calculator.getFlipperType() == PageView.CENTER_RIGHT
						|| calculator.getFlipperType() == PageView.CENTER_LEFT) {
				pageCase = calculatePageCase(startPoint, end,
						calculator.getCorner());
				isAutoFlipper = true;
				if (currentPoint != null) {
					if (timer != null) {
						timer.cancel();
						timer.purge();
						timer = null;
						System.gc();
					}
					timer = new Timer();
					if (tt != null) {
						tt.cancel();
					}
					tt = new TimerTask() {
						@Override
						public void run() {
							if ((currentPoint.getX() < 2 * PageView.this
									.getWidth() && currentPoint.getX() > -PageView.this
									.getWidth())
									&& (currentPoint.getY() > -PageView.this
											.getHeight() && currentPoint.getY() < 2 * PageView.this
											.getHeight())) {
								switch (pageCase) {
								case PageView.PAGE_NEXT_BACK:
									PageView.this.back();
									break;
								case PageView.PAGE_NEXT_NEWPAGE:
									PageView.this.newPage();
									break;
								case PageView.PAGE_PRE_BACK:
									PageView.this.back();
									break;
								case PageView.PAGE_PRE_NEWPAGE:
									PageView.this.newPage();
									break;
								}
							} else {
								if (pageCase == PageView.PAGE_NEXT_NEWPAGE)
									controller.updateNextPage();
								else if (pageCase == PageView.PAGE_PRE_NEWPAGE)
									controller.updateScrollPrePage();
								isFlipper = false;
								postInvalidate();
								isAutoFlipper = false;
								if (timer != null) {
									timer.cancel();
									timer = null;
								}
							}
						}

					};
					timer.schedule(tt, 1, 1);
				}
			}
			downTime  =event.getDownTime();
			eventTime = event.getEventTime();
			click(downTime,eventTime);
			break;
		}
		return true;
	}

	private void click(long startTime,long endTime){
		if(endTime-startTime<200){
			if(Math.abs(startPoint.getX()-end.getX())<50&&Math.abs(startPoint.getY()-end.getY())<50)
			this.activity.openOptionsMenu();
		}
		
	}
	private int calculatePageCase(Point start, Point end, Point corner) {
		if (corner.getX() == 0
				|| (corner.getX() != getWidth() && corner.getY() == 0)) {
			if (end.getX() - start.getX() > 100) {
				return PageView.PAGE_PRE_NEWPAGE;
			} else
				return PageView.PAGE_PRE_BACK;
		} else {
			if (start.getX() - end.getX() > 100) {
				return PageView.PAGE_NEXT_NEWPAGE;
			} else
				return PageView.PAGE_NEXT_BACK;
		}
	}

	private void back() {
		currentPoint.setX(currentPoint.getX() - calculator.getAutoScrollX());
		currentPoint.setY(currentPoint.getY() - calculator.getAutoScrollY());
		postInvalidate();
	}

	private void newPage() {
		currentPoint.setX(currentPoint.getX() + calculator.getAutoScrollX());
		currentPoint.setY(currentPoint.getY() + calculator.getAutoScrollY());
		postInvalidate();
	}

	@Override
	protected void onCreateContextMenu(ContextMenu menu) {
		//super.onCreateContextMenu(menu);
		menu.add(0,ADDNOTE,0,"添加笔记");
		menu.add(0,VIEWNOTE,0,"查看笔记");
		menu.setHeaderTitle("笔记");
		menu.setHeaderIcon(R.drawable.text32);
	}

	Timer timer = null;
	TimerTask tt = null;
	private boolean isAutoFlipper = false;
}
